﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using NetHttp = System.Net.Http;

namespace Reborn.Net.Http.Extension
{
    public static class HttpClientExtension
    {



        public static async Task<Response> TryGetAsync(this NetHttp.HttpClient httpClient, string url, HttpContent httpContent = null)
        {
            Response response = new Response();
            try
            {
                string result = httpClient.GetStringAsync(url).Result;
                response.StatusCode = System.Net.HttpStatusCode.OK;
                response.Content = result;

                return response;
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                MessagePipelines.Error?.Invoke(null, ex);

                response.StatusCode = System.Net.HttpStatusCode.BadRequest;
                response.Content = ex.Message;

                return response;
            }
            catch (Exception ex)
            {
                MessagePipelines.Error?.Invoke(null, ex);

                response.StatusCode = System.Net.HttpStatusCode.BadRequest;
                response.Content = ex.Message;

                return response;
            }
        }

        public static async Task<Response> TryPostAsync(this NetHttp.HttpClient httpClient, string url, HttpContent httpContent = null)
        {
            Response response = new Response();
            try
            {
                var postResult = await httpClient.PostAsync(url, httpContent);
                string result = await postResult.Content.ReadAsStringAsync();
                response.StatusCode = System.Net.HttpStatusCode.OK;
                response.Content = result;

                return response;
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                MessagePipelines.Error?.Invoke(null, ex);

                response.StatusCode = System.Net.HttpStatusCode.BadRequest;
                response.Content = ex.Message;

                return response;
            }
            catch (Exception ex)
            {
                MessagePipelines.Error?.Invoke(null, ex);

                response.StatusCode = System.Net.HttpStatusCode.BadRequest;
                response.Content = ex.Message;

                return response;
            }
        }
    }
}

